package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.RolesT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.DictionariesTService;
import com.cci.kangdao.service.NotifyRecordTService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//消息推送类接口
@Service("NotifyRecordTService")
public class NotifyRecordTServiceImpl implements NotifyRecordTService{

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	private NotifyRecordTDao notifyRecordTDao;
	
	@Autowired
	private PropertiesUtils propertiesUtils;
	
	@Autowired
	private LoginDao loginDao;
	@Resource
	private DictionariesTService dictionariesTService;

	@Resource
	private MailBoxTDao mailBoxTDao;
	@Resource
	private RolesNotifyRecordTDao rolesNotifyRecordTDao;
	@Resource
	private UserFeedbackDao userFeedbackDao;
	@Resource
	private GMApplyRecordTDao gmApplyRecordTDao;
	@Resource
	private CommonNotifyRecordTDao commonNotifyRecordTDao;
	@Resource
	private RolesTDao rolesTDao;
	@Resource
	private NotifyRecordDYDao notifyRecordDYDao;

	//根据用户id和Category获取消息推送集合
	@Transactional
	@Override
	public ModelAndView getNotifyRecordTListByUserIdCategory(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		UserT loginUserT = loginDao.getUserByid(userADId);
		long userid = loginUserT.getId();
		try{
			JSONObject obj = new JSONObject();
			// 分页信息
			int page = 1;   //初始化当前页数
			if (map.get("page") != null) {  //获取前端传来的页数
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));  //每页显示多少条数据
			map.put("start", (page - 1) * pagesize);  
			map.put("pagesize", pagesize);
			PageHelper.startPage(page, pagesize,true);
			map.put("receiverId", userid);
			Long orderId = MapUtils.getLong(map,"orderId");
			map.put("orderId",orderId);
			map.put("sendType",2);
			List<Map<String, Object>> notifyRecordMapList = notifyRecordTDao.getNotifyRecordTListByUserIdCategory(map);
			if(CollectionUtils.isEmpty(notifyRecordMapList)){
				map.put("sendType",1);
				notifyRecordMapList = notifyRecordTDao.getNotifyRecordTListByUserIdCategory(map);
			}
			
			PageInfo info = new PageInfo<>(notifyRecordMapList);
			obj.put("status", 0);
			obj.put("msg", "查询成功!");
			obj.put("data", new JSONObject().put("notifyRecordList", info.getList()));
			//批量已读工单消息
			if(NumberUtils.isPositiveNum(orderId)){
				Map<String,Object> updateMap = new HashMap<>(4);
				updateMap.put("Updator",loginUserT.getId());
				updateMap.put("UpdateTime",LocalTimeUtil.getRealCurrentTime());
				updateMap.put("orderId",orderId);
				updateMap.put("receiverId",loginUserT.getId());
				notifyRecordTDao.updateNotifyRecordTByOrderId(updateMap);
			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);	
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e);
		}
		return null;
	}

	//ge根据id，单击已读
	@Override
	public ModelAndView updateNotifyRecordTById(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		UserT loginUserT = loginDao.getUserByid(userADId);
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间 
		try{
			JSONObject obj = new JSONObject();
			Map<String, Object> notifyRecordTMap = new HashMap<String, Object>();
			notifyRecordTMap.put("Updator", loginUserT.getId());
			notifyRecordTMap.put("UpdateTime", currentTime);
			notifyRecordTMap.put("ID", Long.parseLong((String)map.get("ID")));
			int index = notifyRecordTDao.updateNotifyRecordTById(notifyRecordTMap);
			obj.put("status", 0);
			obj.put("msg", "修改成功!");
			obj.put("data", "");
			ParameterTool.writeResponse(response, obj.toString());	
		} catch(Exception e) {
			log.error(e);
		}
		return null;
	}

	@Override
	public void getWorkOrderNotifyRecordList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		UserT userT = UserThreadLocal.get();
		
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		List<RolesT> rolesTS = rolesTDao.getRoleListByUserID(userT.getId());
		int isConver = 0; //是否转换 (0:否    1:是)
		//ccec渠道当工单状态为31	异常关闭申请中并且登录人只有普通用户角色     做一层转换    让用户看到异常关闭状态 (只有ccec工单有31  异常关闭申请中)
		if(CollectionUtils.isNotEmpty(rolesTS) && rolesTS.size() == 1 && "R0002".equals(rolesTS.get(0).getRolesNo().trim())){
			isConver = 1;
		}
		Integer pageNo = MapUtils.getInteger(map,"pageNo",1);
		Integer defaultPageCount = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
		Integer pageCount = MapUtils.getInteger(map,"pageCount",defaultPageCount);
		
		PageHelper.startPage(pageNo, pageCount,true);
		List<Map<String,Object>> list = notifyRecordTDao.getWorkOrderNotifyRecordList(userT.getId());
		PageInfo pageInfo = new PageInfo<>(list);
		
		List<Map<String,Object>> workOrderMapList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(pageInfo.getList())){
			for(Object o:pageInfo.getList()){
				Map<String,Object> notifyWorkOrderMap = (Map<String, Object>) o;
				Map<String,Object> workOrderMap = new HashMap<>();
				
				workOrderMap.put("orderId",MapUtils.getLong(notifyWorkOrderMap,"OrderId"));
				workOrderMap.put("orderNo",MapUtils.getString(notifyWorkOrderMap,"OrderNo"));
				workOrderMap.put("isRead",MapUtils.getInteger(notifyWorkOrderMap,"IsRead"));
				workOrderMap.put("orderTime",MapUtils.getString(notifyWorkOrderMap,"CreateTime"));
				workOrderMap.put("customerComplaint",MapUtils.getString(notifyWorkOrderMap,"CustomerComplaint"));
				workOrderMap.put("ESN",MapUtils.getString(notifyWorkOrderMap,"ESN"));
				workOrderMap.put("customerName",MapUtils.getString(notifyWorkOrderMap,"CustomerName"));
				workOrderMap.put("guessDistance",MapUtils.getDouble(notifyWorkOrderMap,"GuessDistance",0.0));
				
				// TODO 放入服务工单对应的区域
				workOrderMap.put("CrmPositionName", MapUtils.getString(notifyWorkOrderMap, "CrmPositionName"));
				
				Integer orderStatus = MapUtils.getInteger(notifyWorkOrderMap,"OrderStatus");  //工单状态
				long orderChannel = MapUtils.getLongValue(notifyWorkOrderMap,"OrderChannel");

				String createTime = MapUtils.getString(notifyWorkOrderMap,"CreateTime");
				String updateTime = MapUtils.getString(notifyWorkOrderMap,"UpdateTime");
				//根据工单状态计算工单服务时间
				if(orderStatus == 3 || orderStatus == 15 || orderStatus == 13 || orderStatus == 16 || orderStatus == 5  ||
						orderStatus == 14 || orderStatus == 28 || orderStatus == 29 || orderStatus == 30  || orderStatus == 31) {
					long dealTime = Date_Util.getSubTime(createTime, updateTime, 1);
					workOrderMap.put("dealTime", dealTime);
				}else{
					long dealTime = Date_Util.getSubTime(createTime, currentTime, 1);
					workOrderMap.put("dealTime", dealTime);
				}


				if(orderStatus == 31 && isConver == 1){
					orderStatus = 16;
				}
				workOrderMap.put("orderStatus",orderStatus);
				workOrderMap.put("orderStatusMessage",dictionariesTService.getDictionaryDValueByDInt("OrderStatus",orderStatus));
				workOrderMapList.add(workOrderMap);
			}
		}
		Map<String,Object> dataMap = new HashMap<>(2);
		dataMap.put("totalRecord",pageInfo.getTotal());
		dataMap.put("recordList",workOrderMapList);
		ParameterTool.writeSuccessResponse(response,dataMap);
	}

	@Override
	public void updateNotifyReadStatusByCategory(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		UserT userT = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		Integer category = MapUtils.getInteger(map,"category",0);
		switch (category){
			case 1:
				// 系统公告
				mailBoxTDao.updateIsReadByReceiverId(userT.getId(),userT.getId(),currentTime);
				break;
			case 2:
				// 意见反馈
				userFeedbackDao.updateNotifyReadStatusByReceiverId(userT.getId());
				break;
			case 3:
				// 工单提醒
				notifyRecordTDao.updateNotifyReadStatusByReceiver(userT.getId(),userT.getId(),currentTime);
				break;
			case 4:
				// 权限申请
				rolesNotifyRecordTDao.updateNotifyReadStatusByReceiverId(userT.getId(),userT.getId(),currentTime);
				break;
			case 5:
				//GM权限
				int index = gmApplyRecordTDao.updateNotifyReadStatusByReceiverId(userT.getId(), userT.getId(), currentTime);
				break;
			case 6:
				//主动升级消息
				commonNotifyRecordTDao.updatePushReadStatusByReceiverId("1",null, userT.getId(), currentTime);
				break;
			case 7:
				//CBU消息
				commonNotifyRecordTDao.updatePushReadStatusByReceiverId("2",null, userT.getId(), currentTime);
				break;
			case 8:
				//大运消息
				notifyRecordDYDao.oneKeyReadDYNotifyRecord(userT.getId(),currentTime);
				break;
			case 9:
				//tsr消息
				commonNotifyRecordTDao.updatePushReadStatusByReceiverId("3",null, userT.getId(), currentTime);
				break;
			default:
				ParameterTool.writeResponse(response,1,"未知消息类别");
				return;
		}
		ParameterTool.writeSuccessResponse(response);
	}


}
